package com.neuqsoft.ymtdemo.utils;

import android.os.Looper;
import android.text.TextUtils;
import android.widget.Toast;

import com.alibaba.fastjson.JSONObject;
import com.neuqsoft.ymtdemo.App;
import com.neuqsoft.ymtdemo.bean.OpenIDBean;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import essclib.pingan.ai.request.biap.Biap;
import essclib.pingan.ai.request.biap.common.ApiConstants;
import essclib.pingan.ai.request.biap.net.OkHttpUtils;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * 模拟第三方APP后端提供的签名功能
 *  接入方不可使用该接口！！！！！
 * 签名过程是使用渠道申请的密钥，通过一定的算法，对原始数据进行单向不可逆的操作
 * 出于安全的考虑，渠道的密钥应当保存在后台，因此该方法提供的签名功能应当在APP后台实现
 * 签名方法（模拟后台实现）
 */

public class SignUtil {

    private static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");
    //不带用户信息只传姓名，社保卡号，ak
    public static void sign(String aac002, String aac003, final CallBackNet callBackNet) {
        sign(aac002, aac003, null, null, null,null,null,null,callBackNet);
}
    //带用户信息，多传：发卡地，签发号，手机号aac067 历史数据标志historyFlag 支付必传openID
    public static void sign(String aac002, String aac003, String aab301, String signNo,
                            String aac067,String historyFlag, String openID,String isIndep,final CallBackNet callBackNet) {

        Map data = new HashMap();
        data.put("accessKey", App.accessKey);
        data.put("channelNo", App.channelNo);
        if (!TextUtils.isEmpty(aab301)) {
            data.put("aab301", aab301);
        }
        data.put("aac002", aac002);
        data.put("aac003", aac003);
        data.put("signNo", signNo);
        data.put("aac067",aac067);
        // 历史数据标志historyFlag:传1为历史数据
        data.put("historyFlag",historyFlag);
        if (!TextUtils.isEmpty(openID)){
            data.put("openId",openID);
        }
        //是否为独立服务，传1为是，不传为不是
        data.put("isIndep", isIndep);
        //是否有资格做待遇资格认证，若1年内做过，则不重复测
        if (!TextUtils.isEmpty(App.isAuthFace)){
            data.put("isAuthFace",App.isAuthFace);
        }
        RequestBody body = RequestBody.create(JSON, JSONObject.toJSONString(data));
        String sign = Biap.getInstance().getSign();
        Request request = new Request.Builder()
                .url(sign)
                .post(body)
                .build();
        OkHttpUtils.getInstance().newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                if (callBackNet != null) {
                    callBackNet.onFail(e.getMessage());
                }
            }
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (response.isSuccessful()) {
                    if (callBackNet != null) {
                        Map<String, String> result = JSONObject.parseObject(response.body().string(), Map.class);
                        callBackNet.onSuccess(result.get("result"));
                    }
                }
            }
        });
    }

    //模仿请求后台轮询，得到调起收银台的openID

    public static void getopenID(String typepay,final CallBackNet callBackNet){
//         模式（1 纯医保 2 医保+自费 3 纯自费 4.个账+自费）
//        支付产品（1 线上支付，2 主扫码，3 被扫码）
        final Request request;
        if (App.environmentUrl.equals(ApiConstants.URL_DEV)){
            request = new Request.Builder()
                    .url("http://39.107.84.166:8080/OPENID/"+App.channelNo+"/"+App.signNO+"/"+App.paymoudle+"/"+ App.paymoney+"/"+typepay)
                    .post(RequestBody.create(JSON, ""))
                    .build();
        }else {
            request = new Request.Builder()
                    .url(App.environmentUrl+"/portal/forward/order?service=/OPENID/"+App.channelNo+"/"+App.signNO+"/"+App.paymoudle+"/"+ App.paymoney+"/"+typepay)
                    .addHeader("X-TOKEN", App.token)
                    .post(RequestBody.create(JSON, ""))
                    .build();
        }

        OkHttpUtils.getInstance().newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                callBackNet.onFail(e.getMessage());
            }

            @Override
            public void onResponse(Call call, Response response) {
                OpenIDBean bean = null;
                try {
                    String data = response.body().string();
                    if (!response.isSuccessful()&&!TextUtils.isEmpty(data)){
                        Looper.prepare();
                        Toast.makeText(App.getApp(),"openid接口获取失败",Toast.LENGTH_SHORT).show();
                        Looper.loop();
                        return;
                    }
                    bean = JSONObject.parseObject(data, OpenIDBean.class);
                    if (bean.getMsgCode()==100000){
                        callBackNet.onSuccess(bean.getResult().getOpenid());
                    }else {
                        Looper.prepare();
                        Toast.makeText(App.getApp(),bean.getMsg(),Toast.LENGTH_SHORT).show();
                        Looper.loop();
                    }
                } catch (IOException e) {

                }
            }
        });
    }

    public static void getopenID(String moudle,String money,String typepay,final CallBackNet callBackNet){
//         模式（1 纯医保 2 医保+自费 3 纯自费 4.个账+自费）
//        支付产品（1 线上支付，2 主扫码，3 被扫码）
        final Request request;
        if (App.environmentUrl.equals(ApiConstants.URL_DEV)){
            request = new Request.Builder()
                    .url("http://39.107.84.166:8080/OPENID/"+App.channelNo+"/"+App.signNO+"/"+moudle+"/"+ money+"/"+typepay)
                    .post(RequestBody.create(JSON, ""))
                    .build();
        }else {
            request = new Request.Builder()
                    .url(App.environmentUrl+"/portal/forward/order?service=/OPENID/"+App.channelNo+"/"+App.signNO+"/"+moudle+"/"+ money+"/"+typepay)
                    .addHeader("X-TOKEN", App.token)
                    .post(RequestBody.create(JSON, ""))
                    .build();
        }

        OkHttpUtils.getInstance().newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                callBackNet.onFail(e.getMessage());
            }

            @Override
            public void onResponse(Call call, Response response) {
                OpenIDBean bean = null;
                if (!response.isSuccessful()){
                    Looper.prepare();
                    Toast.makeText(App.getApp(),"openid接口获取失败",Toast.LENGTH_SHORT).show();
                    Looper.loop();
                    return;
                }
                try {
                    bean = JSONObject.parseObject(response.body().string(), OpenIDBean.class);
                    if (bean.getMsgCode()==100000){
                        callBackNet.onSuccess(bean.getResult().getOpenid());
                    }else {
                        Looper.prepare();
                        Toast.makeText(App.getApp(),bean.getMsg(),Toast.LENGTH_SHORT).show();
                        Looper.loop();
                    }

                } catch (IOException e) {

                }
            }
        });
    }

    public interface CallBackNet {

        void onSuccess(String data);

        void onFail(String data);
    }

}
